package com.appology.chuck;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.*;

import com.appology.jokes.Joke;
import com.appology.users.ChuckUser;
import com.appology.users.ChuckUserHelper;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * This is the main servlet of the app. It responds with a simple Chuck Norris
 * joke if the user is not signed in, A joke that has the user's username if
 * they are signed in, but did not grant the buzz permissions to the app, and
 * finally a joke with their full name if they have signed in and granted Buzz
 * permisions
 * 
 */

@SuppressWarnings("serial")
public class BetterthanchuckServlet extends HttpServlet {

	private static ChuckUser chuckUser;
	private static UserService userService;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		// Set the content type as text/html, and set the headers to explicitly
		// disallow caching in the browser. We always want a fresh copy of
		// whatever this page has to say
		resp.setContentType("text/html");
		resp.setHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
		resp.setHeader("Last-Modified", new Date().toString());
		resp.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
		resp.setHeader("Pragma", "no-cache");

		// Get the current Google user making the request
		userService = UserServiceFactory.getUserService();

		// If the user is logged in
		if (userService.getCurrentUser() != null) {

			// Get the ChuckUser from the ChuckUserHelper using the user's
			// Google Id
			// We need that because it contains their proper display name.
			chuckUser = ChuckUserHelper.getChuckUserByGoogleId(userService
					.getCurrentUser().getUserId());

			// If the ChuckUser exists
			// If this object is null, then it means the user has logged in,
			// but did not grant us the permission to access his or her Buzz
			// account.
			// In that case we will just user his or her Google username i.e.
			// the bit before @gmail.com
			if (chuckUser == null) {

				// Get a random joke with the user's Google username
				resp.getWriter().println(
						Joke.getInstance().getRandom(
								userService.getCurrentUser().getNickname()));
			} else {

				// Get a random joke with the user's proper display name
				resp.getWriter().println(
						Joke.getInstance()
								.getRandom(chuckUser.getDisplayName()));
			}

		} else {

			// If the user is not logged in at all, then just give them a random
			// Chuck Norris joke with no name replacement.
			resp.getWriter().println(Joke.getInstance().getRandom(null));

		}

	}

}
